<?php

/***  DOCUMENTATION LAYER

	Greqo Blogger Library

	Last Update: Mar 2007
	Author: Tom Atwell (klenwell@gmail.com)

	FUNCTIONS
		greqo_blogger_set_user_data($user, $password, $blog_id)
		greqo_blogger_get_user_data()
		
		greqo_blogger_get_api_url($force=1)
		greqo_blogger_set_api_url($url)
		greqo_blogger_request_api_url($force=0)
		
		greqo_atom_to_array($xml_string)
		greqo_blogger_parse_post_response($xml_string)
		greqo_escape_entities($string)

  NOTES
		$_SESSION['GDATA']['BLOGGER']['api_url'] manages Blogger API request url
		
		Global values set by greqo_blogger_set_user_data:
			$GREQO['BLOGGER']['user']
			$GREQO['BLOGGER']['password']
			$GREQO['BLOGGER']['blog_id']

______________________________________________________________________________*/


// greqo_blogger_set_user_data
/*____________________________________________________________________________*/
function greqo_blogger_set_user_data($user, $password, $blog_id, $is_old_account=0) 
{
// *** DATA

	// global
	global $GREQO;
	
	// old account deprecation flag
	$_FLAG['old_accounts_now_deprecated'] = 0;

	// Return (void)

// *** MANIPULATE

	// globalize values
	$GREQO['BLOGGER']['user'] = $user;
	$GREQO['BLOGGER']['password'] = $password;
	$GREQO['BLOGGER']['blog_id'] = $blog_id;
	
	// old account flag
	if ( !$_FLAG['old_accounts_now_deprecated'] && $is_old_account )
	{
		$GREQO['BLOGGER']['is_old_account'] = 1;
	}
	else
	{
		$GREQO['BLOGGER']['is_old_account'] = 0;
	}
	
	return $GREQO['BLOGGER'];

} // end Fx
/*____________________________________________________________________________*/



// greqo_blogger_get_user_data
/*____________________________________________________________________________*/
function greqo_blogger_get_user_data() 
{
// *** DATA

	// global
	global $GREQO;
	
	// Internal
	$_FLAG['err'] = 0;

	// Return
	$DATA = array();
	

// *** MANIPULATE

	// user name
	if ( empty($GREQO['BLOGGER']['user']) )
	{
		trigger_error('blogger user name not set', E_USER_WARNING);
		$_FLAG['err'] = 1;
	}
	
	// password
	if ( empty($GREQO['BLOGGER']['password']) )
	{
		trigger_error('blogger password not set', E_USER_WARNING);
		$_FLAG['err'] = 1;
	}
	
	// blog id (not required for blog list id)
	if ( empty($GREQO['BLOGGER']['blog_id']) )
	{
		trigger_error('blogger blog_id not set', E_USER_NOTICE);
	}
	
	// error?
	if ( $_FLAG['err'] ) return 0;
	
	// package data
	$DATA = array
	(
		'user' => $GREQO['BLOGGER']['user'],
		'password' => $GREQO['BLOGGER']['password'],
		'blog_id' => $GREQO['BLOGGER']['blog_id'],
	);
	
	
// * Return

	return $DATA;

} // end Fx
/*____________________________________________________________________________*/



// greqo_blogger_get_api_url
/*____________________________________________________________________________*/
function greqo_blogger_get_api_url($force=1) 
{
// *** DATA
	
	// Session value
	$_SESSION['GDATA']['BLOGGER']['api_url'] = ( !empty($_SESSION['GDATA']['BLOGGER']['api_url']) ) ? $_SESSION['GDATA']['BLOGGER']['api_url'] : '';

	// Return
	$blogger_api = '';

// *** MANIPULATE

	// request url is empty or forced
	if ( $force || empty($_SESSION['GDATA']['BLOGGER']['api_url']) )
	{
		if ( !greqo_blogger_request_api_url() )
		{
			return 0;
		}
	}

	// return $_SESSION['GDATA']['BLOGGER']['api_url']
	$blogger_api = $_SESSION['GDATA']['BLOGGER']['api_url'];
	
	// * Debug
	if ( 0 ) echo "<p>{$blogger_api}</p>";
	
// *** RETURN

	return $blogger_api;

} // end Fx
/*____________________________________________________________________________*/



// greqo_blogger_set_api_url
/*____________________________________________________________________________*/
function greqo_blogger_set_api_url($url) 
{
// *** DATA

	// Return (void)
	// sets $_SESSION['GDATA']['BLOGGER']['api_url']

	
// *** MANIPULATE

	// sanity check
	if ( empty($url) )
	{
		trigger_error('blogger api url value is empty', E_USER_WARNING);
	}

	// set value
	$_SESSION['GDATA']['BLOGGER']['api_url'] = $url;

	
// *** RETURN

	return;

} // end Fx
/*____________________________________________________________________________*/



// greqo_request_blogger_api_url
// Returns and sets global value for $GREQO['BLOGGER']['api_url']
/*____________________________________________________________________________*/
function greqo_blogger_request_api_url() 
{
// *** DATA

	// Global
	global $GREQO;

	// Client Parameters
	$request_url = $GREQO['BLOGGER']['request_url'];
	
	// Internal
	$_FLAG['api_ok'] = 0;

	// Return (void)
	// sets api url value, returns 1 on success, 0 on failure
	

// *** MANIPULATE
	
	// Set session token
	$session_token = greqo_get_clientlogin_token();
	
	// HTTP Request using PEAR client

		// Call PEAR Classes
		greqo_load_gdata_classes();
	
		// PEAR Http Config
		$_CONFIG = array( 'timeout' => 10, 'maxRedirects' => 0 );	
		
		// Create PEAR Client
		$GDATA_CLIENT = new HTTP_Request($request_url, $_CONFIG);
		$GDATA_CLIENT->setMethod(HTTP_REQUEST_METHOD_GET);
	
		// Build Request
		$GDATA_CLIENT->addHeader('Authorization', 'GoogleLogin auth=' . $session_token);
	
		// Send Request
		$GResult = $GDATA_CLIENT->sendRequest();
	
		// Check for Errors
		if ( PEAR::isError($GResult) )
		{
			trigger_error('request failed: ' . $GResult->getMessage(), E_USER_WARNING);
			return 0;
		}
	
	// Get Response Data
	
		// Get Code and Body
		$_code = $GDATA_CLIENT->getResponseCode();
		$_code_class = floor($_code / 100);
		$_response = $GDATA_CLIENT->getResponseBody();

		
	// Process Results, pick location
	if ( $_code_class == 2 )
	{
		if ( preg_match("|(http://[^/]+)|si", $request_url, $_MATCH) ) $api_url = $_MATCH[1];
	}
	elseif ( $_code_class == 3 )
	{
		if ( !$_location = $GDATA_CLIENT->getResponseHeader('Location') )
		{
			$_response = htmlspecialchars($_response);
			trigger_error("no location in response (code $_code): $_response", E_USER_WARNING);
			return 0;
		}
		if ( preg_match("|(http://[^/]+)|si", $_location, $_MATCH2) ) $api_url = $_MATCH2[1];
	}
	else
	{
		$_response = htmlspecialchars($_response);
		trigger_error("unexpected response (code $_code): $_response", E_USER_WARNING);
		return 0;
	}
	
	// sanity check
	if ( empty($api_url) ) 
	{
		trigger_error('failed to get blogger api url', E_USER_WARNING);
		return 0;
	}
	
	// set blogger api url
	greqo_blogger_set_api_url($api_url); 
	

// *** RETURN

	return 1;

} // end Fx
/*____________________________________________________________________________*/



// greqo_atom_to_array
/*____________________________________________________________________________*/
function greqo_atom_to_array($xml_string) 
{
// *** DATA

	// Debug
	$_FLAG['debug'] = 0;

	// Return
	$ARRAY = array();


// *** MANIPULATE

	// include parser file
	require_once(MAGPIE_PATH);
	
	// build parser
	$MagpieParser = new MagpieRSS( $xml_string );
	
	// dump in array
	if ( $MagpieParser && !$MagpieParser->ERROR )
	{
		$xml = print_r($MagpieParser, 1); 
		if ( $_FLAG['debug'] ) echo "<div style='margin:1em; padding:1em; border:1px solid red;'><pre>$xml</pre></div>";
		foreach ( $MagpieParser->channel as $_ARR ) $ARRAY['CHANNEL'][] = $_ARR;
		foreach ( $MagpieParser->items as $_ARR ) $ARRAY['ITEM'][] = $_ARR;
	}
		
	// error
	else
	{
		trigger_error("Error: " . $rss->MagpieParser, E_USER_WARNING);
	}
	

// *** RETURN

	return $ARRAY;

} // end Fx
/*____________________________________________________________________________*/



// greqo_blogger_parse_post_response
/*____________________________________________________________________________*/
function greqo_blogger_parse_post_response($xml_string) 
{
// *** DATA

	// Regex Expressions
	$link_regex = "%<link\s*rel='[^']*'\s*type='[^']*'\s*href='([^']*)'%i";
	#$id_regex = '%<id>(.*(?=</id>))%i';

	// Return
	$POST_DATA = array
	(
		'id' => 0,
		'self_link' => '',
		'edit_link' => '',
	);


// *** MANIPULATE

	// regex
	if ( !preg_match_all($link_regex, $xml_string, $_LINK) )
	{
		trigger_error('unable to parse response:' . htmlspecialchars($xml_string), E_USER_NOTICE);
		return 0;
	}
	
	$self_link = $_LINK[1][0];
	$edit_link = $_LINK[1][1];
	$id = substr($edit_link, strrpos($edit_link,'/')+1);
	
	$POST_DATA = array
	(
		'id' => $id,
		'self_link' => $self_link,
		'edit_link' => $edit_link,
	);
	

// *** RETURN

	return $POST_DATA;

} // end Fx
/*____________________________________________________________________________*/



// greqo_escape_entities
// credit: http://www.php.net/manual/en/function.htmlspecialchars.php#46693
/*____________________________________________________________________________*/
function greqo_escape_entities($string) 
{
// *** DATA

	// Return
	$escaped_string = '';

// *** MANIPULATE

	// globalize values
	$string = htmlspecialchars($string, ENT_QUOTES);
	$string = preg_replace('/&#0*39;/', '&apos;', $string);
	
// *** RETURN

	return $string;

} // end Fx
/*____________________________________________________________________________*/

?>
